package net.zjitc.demo1.Controller;

import net.zjitc.demo1.pojo.Message;
import net.zjitc.demo1.pojo.Result;
import net.zjitc.demo1.pojo.ResultData;
import net.zjitc.demo1.pojo.User;
import net.zjitc.demo1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result add(@RequestBody User user) {

        try {
            userService.add(user);
        } catch (Exception e) {
            return new Result(false,Message.ADD_USER_FAIL);
        }
        return new Result(true,Message.ADD_USER_SUCCESS);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id) {
        try {
            userService.deleteById(id);
        } catch (Exception e) {
            return new Result(false,Message.DELETE_USER_FAIL);
        }
        return new Result(true,Message.DELETE_USER_SUCCESS);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        try {
            userService.update(user);
        } catch (Exception e) {
            return new Result(false,Message.EDIT_USER_FAIL);
        }
        return new Result(true,Message.EDIT_USER_SUCCESS);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        ResultData<User> user;
        try {
            user = userService.findById(id);
        } catch (Exception e) {
            return new Result(false,Message.QUERY_USER_FAIL);
        }
        return new Result(true,Message.QUERY_USER_SUCCESS,user);
    }

    @PostMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize, @RequestBody User user) {
        ResultData<User> page=null;
        try {
            page = userService.findPage(currentPage, pageSize, user);
        }   catch (Exception e){
            return new Result(false, Message.QUERY_USER_FAIL, null);
        }
        return new Result(true, Message.QUERY_USER_SUCCESS, page);
    }
}
